<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="放弃入职列表"
        :breadCrumb="['人事', '人事管理', '放弃入职']"
        :showBack="false"
      ></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div style="display: flex">
            <a-select :options="options" v-model="keyWold" />
            <a-input-search
              @press-enter="search"
              @search="search"
              v-model="keyWoldValue"
              placeholder="请输入"
            />
          </div>
          <a-input-search
            @press-enter="search"
            @search="search"
            v-model="phoneData"
            placeholder="输入手机号码搜索"
          />
          <a-button @click="reset">重置</a-button>
        </a-space>
      </template>
      <template #right>
        <a-dropdown
          @popup-visible-change="handleBatchVisible"
          v-model:popup-visible="showBatch"
          @select="handleBatch"
        >
          <a-button type="outline">批量操作</a-button>
          <template #content>
            <a-doption :value="1">批量删除</a-doption>
            <a-doption :value="2">批量转入职申请</a-doption>
          </template>
        </a-dropdown>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
      />
      <a-table-column :width="150" fixed="right">
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-tooltip content="查看详情">
            <icon-font
              type="icon-details-def"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="删除" position="left">
            <a-popconfirm
              content="确定删除吗?"
              position="left"
              @ok="del(record.id)"
            >
              <icon-font
                @click="del(record.id)"
                type="icon-delete"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
              />
            </a-popconfirm>
          </a-tooltip>
          <a-tooltip content="更多功能">
            <a-dropdown
              @select="(value: number, e: Event, id: number) => moreItemControl(value, e, record)"
            >
              <icon-font
                type="icon-more-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="singleControl(record)"
              />
              <template #content>
                <a-doption :value="1">转入职申请</a-doption>
              </template>
            </a-dropdown>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>

  <FormHeaderControlSetting
    title="放弃入职表头设置"
    v-model:visible="setting"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
  <a-modal v-model:visible="templateVisible" :width="800" @ok="templateOk">
    <template #title> 更换人员模板 </template>
    <a-input-search
      @press-enter="templateSearch"
      @search="templateSearch"
      v-model="templatekeyWoldValue"
      style="width: 200px; margin-bottom: 20px"
      placeholder="请输入"
    />
    <a-table
      @select="selectId"
      :columns="templateColumns"
      row-key="id"
      :data="templateData.data"
      :row-selection="{
        type: 'radio'
      }"
    />
  </a-modal>
</template>
<script setup lang="tsx">
import { Message } from '@arco-design/web-vue';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import clonedeep from 'lodash.clonedeep';
import {
  GetOnboardingWords,
  OnboardingExcel,
  PutPersonnelid,
  EOabcdegiilmnnooprrtx,
  GetOnboarding,
  EditOnboardingNode,
  DelOnboarding,
  AddStaff,
  AddPositionManage,
  PostOnboardingWords,
  GetManual
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  ChangeHumanInductionState,
  DelHumanList
} from '@/apis/management/personnel/changeManagement/inductionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { ExportHumanRosterList } from '@/apis/management/human/humanRoster';
import {
  PutHeaderSetting,
  GetHeaderSetting,
  PostHeaderSetting
} from '@/apis/management/base/index';
import {
  GetWorkPlaceList,
  GetOrganizationList
} from '@/apis/management/organization/organizationManagement';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { useRouter } from 'vue-router';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import EntryTable from '../entryTable';
import { GetStaff } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { PersonnelListParams } from '@/apis/management/personnel/baseSetting/TransactionSetting/type';
import TableTurn, { type paramsType } from '@/components/TableTurn/index.vue';
import { Modal, Button } from '@arco-design/web-vue';
// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

const templateId = ref(0);
const isSelectId = ref(0);
const templateVisible = ref(false);
const templatekeyWoldValue = ref('');
const templateData: any = reactive({ data: [] });
const templateColumns = [
  {
    title: '人员信息模板名称',
    dataIndex: 'name'
  },
  {
    title: '模板内容',
    dataIndex: 'remark'
  }
];
const selectId = (e: (number | string)[]) => {
  templateId.value = e[0] as number;
};
const templateSearch = async () => {
  const res2: any = await GetHumanTemplateList({
    page: 1,
    size: -1,
    name: templatekeyWoldValue.value
  });
  templateData.data = res2.content;
};
const templateOk = async () => {
  if (templateId.value) {
    await PutPersonnelid({
      id: isSelectId.value,
      personnelId: templateId.value
    });
    isSelectId.value = 0;
    templateId.value = 0;
  } else {
    Message.error('请选择人员模板');
  }
};
const EntryNotice = (data: any) => {
  router.push({
    name: 'EntryNotice',
    query: { id: data.key }
  });
};
const tables = ref();
let exportSettingVisible = ref(false); // 导出弹出框
let importVisible = ref(false); // 导入弹出框
let forbidList: string[] = []; // 必选的表头
const router = useRouter();
let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据

const getTableData = async (params: paramsType) => {
  try {
    const res = await GetStaff({
      ...params,
      typeName: '8',
      [keyWold.value]: keyWoldValue.value,
      mobile: phoneData.value
    });

    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 储存要特殊处理的数据
const showInfoData = reactive({
  data: {
    deptList: [], // 组织列表数据
    workPlaceList: [], // 工作地点数据
    positionList: [] // 职位列表数据
  }
});

// 新增表头
const addHeader = async () => {
  //SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB
  try {
    const {
      funcCtlInfos: { children }
    } = await GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    });

    let headerListCode: any = [];
    children?.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 4,
      headerListCode: headerListCode.join(',')
    });

    init();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 初始化数据
const init = async () => {
  const [
    headerSettingRes,
    businessModalDataRes,
    humanListRes,
    deptListRes,
    workPlaceListRes,
    positionListRes
  ] = await Promise.all([
    // 获取表头
    GetHeaderSetting({
      ownerFuncType: 4,
      userId: +(localStorage.getItem('userId') as string)
    }),
    // 控件数据
    GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    }),
    // 人员列表
    GetHumanTemplateList({
      pageNumber: 0,
      pageSize: -1
    }),
    // 组织列表
    GetOrganizationList({}),
    // 工作地点
    GetWorkPlaceList({
      pageNumber: 0,
      pageSize: -1
    }),
    GetPosition({
      pageNumber: 0,
      pageSize: -1
    })
  ]);

  orginHeaderList.value = headerSettingRes;
  headerSetting.value = [];
  const headerChildren = businessModalDataRes.funcCtlInfos.children;
  headerChildren.forEach((child: any, index: number) => {
    headerSetting.value.push({
      collectionName: child.subDetail.cnName,
      collectionCode: child.subDetail.subCode,
      heads: child.subDetail.subRelDetail.map((subDetail: any) => {
        const isDefault = headerSettingRes.headerListCode.includes(
          subDetail.ctlCode
        );
        return {
          ...subDetail,
          isDefault
        };
      })
    });
  });
  if (headerSettingRes.headerListCode.length < 1) {
    addHeader();
  }
  showInfoData.data.deptList = flatTree(dataTreeFilter(deptListRes));
  showInfoData.data.workPlaceList = workPlaceListRes.content;
  showInfoData.data.positionList = positionListRes.content;
};
init();

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C2818BAA63AE848AA845DA2E81ECB1843'
];

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 4,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error: unknown) {
    console.log(error);
  }
};

let showBatch = ref(false);
// 批量操作
const handleBatchVisible = () => {
  if (selectedList.value.length === 0) {
    Message.error('请先选择数据');
    showBatch.value = false;
    return;
  }
};

const ids = ref();
const goDetail = (data: any) => {
  console.log(111, data);
  router.push({
    name: 'EditTemplate',
    query: { id: data.id, node: 1 }
  });
};

// 模糊查询参数
const options = reactive([
  { label: '名字', value: 'name' },
  { label: '职位', value: 'position' }
]);
// 模糊类型
const keyWold = ref('name');
// 模糊查询值
const keyWoldValue = ref('');

const handleBatch = (key: number) => {
  isMoreSelect.value = true;
  switch (key) {
    // 删除
    case 1:
      del(null);
      break;
    // 转入职申请
    case 2:
      moreItemControl(1, '转入职申请');
      break;
    default:
      break;
  }
};

// 删除人员
const del = async (id: number | null) => {
  if (!id) {
    if (selectedList.value.length === 0) {
      Message.error('请至少选择一项！');
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选中的数据吗？',
        onOk: async () => {
          try {
            await DelHumanList({
              ids: selectedList.value
            });
            tableRef.value.selectedList = [];
            refresh();
          } catch (error: unknown) {
            console.log(error);
          }
        }
      });
    }
  } else {
    await DelHumanList({
      ids: [id]
    });
    tableRef.value.selectedList = [];
    refresh();
  }

  // const onOk = async () => {
  //   if (!id && selectedList.value.length < 1) {
  //     Message.error('请至少选择一项!');
  //     return;
  //   }
  //   await DelHumanList({
  //     ids: selectedList.value.length > 0 ? selectedList.value : [id]
  //   });
  //   refresh();
  // };

  // Modal.open({
  //   title: '删除',
  //   content: <h3> 是否确认删除选中的人员？</h3>,
  //   onOk
  // });
};
let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
let isMoreSelect = ref(false); // 判断是否批量
// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
  isMoreSelect.value = false;
};
const moreItemControl = async (
  key: number,
  e: Event | string,
  record?: any
) => {
  try {
    let title = e?.target?.innerText || e;
    let content: any;
    let onOk: (() => void) | undefined;
    switch (key) {
      case 1:
        content = <>是否确认转入职办理？</>;
        onOk = async () => {
          await ChangeHumanInductionState({
            ids: isMoreSelect.value ? selectedList.value : [singleSelectId],
            type: 4
          });
          refresh();
        };

        break;
    }
    Modal.open({
      title,
      content,
      onOk
    });
  } catch (error: unknown) {
    console.log(error);
  }
};
// 是否显示表头
const isHeaderSetting = async () => {
  try {
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};
const phoneData = ref('');
const search = () => {
  refresh();
};

// 重置数据
const reset = () => {
  keyWold.value = 'name';
  keyWoldValue.value = '';
  phoneData.value = '';
  refresh();
};
// 刷新列表
const refresh = (page?: any) => {
  tableRef.value.loadData(page);
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;

  // 弄出一个小的圆形
}
.arco-btn {
  margin-right: 20px;
}
</style>
